const http = require('http')
const url = require('url')
const mime = require('mime')

const ReadFile = require('./readfile')

const Expire = {
    maxAge: 60 * 60 * 1000,
    exg: /(png|js|css|jpg)$/ig
}


const serve = http.createServer(async function(request, response){
    let pathname = url.parse(request.url).pathname
    if (pathname === '/') {
        pathname = '/index.html'
    }
    const fileHander = new ReadFile(pathname)
    if (fileHander.exist) {
        try {
            const date = new Date()
            const UTCTime = new Date(date.getTime() + Expire.maxAge).toUTCString()
            const {mtime} = await fileHander.stats()
            const file = await fileHander.readFile()
            console.log(fileHander.extname)
            if (Expire.exg.test(fileHander.extname)) {
                // 设置强缓存 cache-control expire
                // response.setHeader('Cache-Control', `no-store`)
                // response.setHeader('Expires', UTCTime)
                // 设置强缓存 end


                // 设置协商缓存
                /* 
                *  ctime  文件最后修改日期
                */
                if (mtime.toUTCString() !== request.headers['if-modified-since']) {
                    response.setHeader('Last-Modified', mtime.toUTCString())
                    response.writeHeader(200, mime.getType(fileHander.extname))
                    response.write(file, 'binary')
                    response.end()
                } else {
                    response.writeHeader(304, mime.getType(fileHander.extname))
                }
                
            } else {
                response.writeHeader(200, mime.getType(fileHander.extname))
                response.write(file, 'binary')
                response.end()
            }
            
            
            
        } catch(e) {
            response.writeHeader(500, {
                'Content-type': 'text/plain'
            })
            response.end(JSON.stringify(e))
        }
        
    } else {
        response.writeHeader(404, {
            'Content-type': 'text/plain'
        })
        response.end('file is not exist')
    }
   
})

serve.listen(2001)
console.log('server is start')
